<template>
  <el-dialog :title="title" width="90vw" :modelValue="modelValue" @close="handleClose" draggable align-center :close-on-click-modal="false">
    <div class="h-[80vh] flex" style="flex-direction: column">
      <div>
        <!-- <div @click="TrackingSearchRef.open()">423442</div> -->
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="formData" :originOption="originOption" @submit="handleSubmitForm" @reset="handleSubmitForm" />
        <div class="bg-[var(--base-border-color)] h-[1px] mb-[8px]"></div>
        <div class="p-[16px] bg-[var(--base-table-hover-bg-color)] mb-[8px]">
          <div class="ml-[4px] flex items-center">
            <div class="flex-1 mr-[16px]">
              <VText title="SKU" :value="skuInfo.sku" :line="1" />
            </div>
            <VText title="ASIN" :value="skuInfo.asin" :line="1" />
          </div>
          <VText title="产品名称" :value="skuInfo.sku_cn_title" :line="1" />
        </div>
      </div>
      <div class="flex-1">
        <vxe-grid v-bind="orderOptions" ref="tableRef" height="600" />
      </div>
    </div>
    <template #footer>
      <el-button @click="handleClose"> 关闭 </el-button>
    </template>
    <TrackingSearch ref="TrackingSearchRef" />
  </el-dialog>
</template>

<script setup lang="jsx">
import { computed, nextTick, watch } from "vue"
import XForm from "@/components/XForm/index.vue"

import TrackingSearch from "./TrackingSearch"
const TrackingSearchRef = ref()

import { getWarehouseOptions, purchaseHistoryList, amazonListingOrderList, amazonListingWaitShipOrderList, listingGetGoods } from "@/api/amazon"
import { ElMessageBox } from "element-plus"
const formOption = ref({ inline: true, option: true, showResetButton: true, submitButtonText: "查询" })
const formData = ref({
  noRange: { type: "order_no", value: "" },
  timeRange: { type: "create_time", value: [] },
})

const title = ref("FBA在途")
const modelValue = ref(false)
const emit = defineEmits(["refresh", "close"])
const skuInfo = ref({})
const tableRef = ref()

import action from "@/utils/action.js"
// 跳转头程单详情
const gotoTcDtl = (row) => {
  action.setGlobalState({
    changeMicoTabsPath: {
      type: "push",
      path: `/head_procedure/orderManagement/fbaOrderManagement/detail`,
      query: {
        id: row.order_id,
      },
    },
  })
}
// 查询
const handleSubmitForm = async () => {
  tableRef?.value.commitProxy("query")
}
// 枚举 数据
const originOption = ref({})
onMounted(() => {
  getWarehouseOptions().then((res) => {
    originOption.value.warehouse = res.data
  })
})
const fieldList = ref([
  {
    field: "noRange",
    placeholder: "可批量搜索",
    type: "textarea",
    select: [
      { label: "头程单号", value: "order_no" },
      { label: "Shipmentid", value: "shipment_id" },
      { label: "ASIN", value: "asin" },
      { label: "SPU", value: "spu" },
    ],
    style: { width: "200px" },
  },
  {
    field: "timeRange",
    type: "dateTimeRangeNorm",
    select: [
      { label: "创建时间", value: "create_time" },
      { label: "计划发货时间", value: "plan_shipment_time" },
      { label: "发货时间", value: "shipment_time" },
    ],
  },
  {
    field: "status",
    type: "select",
    multiple: true,
    collapseTags: true,
    options: {
      placeholder: "备货单状态",
      data: [
        { label: "部分发货", value: "5" },
        { label: "已发货", value: "6" },
        { label: "部分收货", value: "8" },
        { label: "差异收货", value: "9" },
        { label: "已收货", value: "10" },
        { label: "部分退货", value: "12" },
        { label: "全部退货", value: "13" },
        { label: "更改目的仓", value: "14" },
      ],
    },
    style: { width: "200px" },
  },

  {
    field: "to_warehouse_id",
    type: "select",
    originField: "warehouse",
    multiple: true,
    collapseTags: true,
    options: { placeholder: "收货仓" },
    style: { width: "200px" },
  },
  {
    field: "send_warehouse_id",
    type: "select",
    originField: "warehouse",
    multiple: true,
    collapseTags: true,
    options: { placeholder: "发货仓" },
    style: { width: "200px" },
  },
])

const orderOptions = reactive({
  border: true,
  loading: false,
  rowConfig: { height: "auto" },
  showOverflow: false,
  resizable: true,
  columns: [
    {
      field: "order_no",
      title: "头程单号",
      width: 160,
      slots: {
        default: ({ row }) => (
          <div>
            <VText value={row.order_no} line={1} type="link" onClick={() => gotoTcDtl(row)} copy />
          </div>
        ),
      },
    },
    {
      width: 150,
      slots: {
        header: ({}) => (
          <div>
            <div>Shipment ID </div>
            <div>包裹号</div>
          </div>
        ),
        default: ({ row }) => (
          <div class="text-[var(--base-sub-text-color)]">
            <VText value={row.to_order_no} line={1} copy />
            <div>{row.send_warehouse_id}</div>
          </div>
        ),
      },
    },

    {
      minWidth: 200,
      title: "仓库/运输方式/跟踪号 物流商单号",
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="仓库" value={row.send_warehouse} line={1} />
            <VText title="运输方式" value={row.transport_type_desc} line={1} class="text-green" />
            <VText title="跟踪号" value={row.tracking_number} line={1} copy />
          </div>
        ),
      },
    },
    {
      width: 150,
      title: "收货仓库\n亚马逊仓库代码",
      slots: {
        default: ({ row }) => (
          <div>
            <VText value={row.to_warehouse_name || ""} line={1} />
            <VText value={row.to_warehouse_code} line={1} />
          </div>
        ),
      },
    },

    {
      minWidth: 120,
      title: "总运费(CNY)",
      slots: {
        default: ({ row }) => (
          <div>
            <VText value={row.freight_fee} line={1} class="text-red" />
          </div>
        ),
      },
    },
  ],
  pagerConfig: {
    pageNum: 1,
    pageSize: 10,
  },
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: async ({ page }) => {
        let param = {
          ...formData.value,
          sku: skuInfo.value.sku,
          asin: skuInfo.value.asin,
          shop_id: skuInfo.value.shop_id,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        }
        param[param.noRange.type] = param.noRange.value.split("\n").filter((v) => !!v.trim())
        param[param.timeRange.type] = param.timeRange?.value || []
        if (pageType.value == "wait") {
          param.wait_ship = 1
        }
        const res = await amazonListingWaitShipOrderList(param)
        // console.log(res)
        return res
      },
    },
  },
})

const handleClose = () => {
  modelValue.value = false
  formData.value = {}
  formData.value.noRange = { type: "order_no", value: "" }
  formData.value.timeRange = { type: "create_time", value: "" }
}
// 头程已发货记录 列配置
const routeColums = [
  { field: "weighted_freight_fee", title: "加权运费", width: 100 },
  { field: "purchase_cost", title: "加权采购成本", width: 120 },
  {
    width: 130,
    slots: {
      header: ({}) => (
        <div>
          <div class="font-bold">发货数量</div>
          <div>发货时间</div>
        </div>
      ),
      default: ({ row }) => (
        <div class="text-[var(--base-sub-text-color)]">
          <div class="text-red font-bold">{row.shipped_quantity}</div>
          <VText value={row.shipment_time || ""} line={1} />
        </div>
      ),
    },
  },
  {
    width: 130,
    slots: {
      header: ({}) => (
        <div>
          <div class="font-bold">在途数量</div>
          <div>预计到货时间</div>
        </div>
      ),
      default: ({ row }) => (
        <div class="text-[var(--base-sub-text-color)]">
          <div class="text-red font-bold">{row.transit_num}</div>
          <VText value={row.plan_arrival_time || ""} line={1} />
        </div>
      ),
    },
  },

  {
    width: 130,
    slots: {
      header: ({}) => (
        <div>
          <div class="font-bold">收货数量</div>
          <div>收货时间</div>
        </div>
      ),
      default: ({ row }) => (
        <div class="text-[var(--base-sub-text-color)]">
          <VText value={row.received_quantity} class="text-green font-bold" line={1} />
          <VText value={row.received_time || ""} line={1} />
        </div>
      ),
    },
  },
  {
    field: "status_desc",
    title: "状态",
    width: 100,
    slots: {
      default: ({ row }) => (
        <div>
          <VText value={row.status_desc} line={1} />
          {row.status_desc == "已发货" ? <el-button onClick={() => backupWarehouse(row)}> 完结 </el-button> : ""}
        </div>
      ),
    },
  },

  {
    width: 140,
    title: "物流状态/实际时间",
    slots: {
      default: ({ row }) => (
        <div>
          <VText value="查看详情" type="link" onClick={() => TrackingSearchRef.value.open({ sku: row.sku, customer_order_no: row.order_no })} />
        </div>
      ),
    },
  },

  { field: "shipment_status", title: "货件状态", width: 100 },

  {
    width: 140,
    title: "备货/运输/总天数",
    slots: {
      default: ({ row }) => (
        <div>
          <VText title="备货" value={row.stock_in_days + "天"} line={1} />
          <VText title="运输" value={row.transport_days + "天"} line={1} />
          <VText title="总天数" value={row.stock_in_days + row.transport_days + "天"} line={1} />
        </div>
      ),
    },
  },

  // { field: "to_asin", title: "包含的ASIN", width: 100 },
  { field: "order_remark", title: "单据备注", width: 100 },
]
// 头程待发货记录 列配置
const waitColums = [
  {
    minWidth: 140,
    title: "需求数量\n建单时间",
    slots: {
      default: ({ row }) => (
        <div>
          <VText title="需求数量" value={row.quantity} line={1} />
          <VText title="建单时间" value={row.create_time} line={1} />
        </div>
      ),
    },
  },

  { field: "plan_shipment_time", title: "预计发货时间", width: 140 },
  {
    field: "status_desc",
    title: "状态",
    width: 120,
    slots: {
      default: ({ row }) => (
        <div>
          <VText value={row.status_desc} line={1} />
        </div>
      ),
    },
  },
  { field: "shipment_status", title: "货件状态", width: 120 },
  { field: "order_remark", title: "单据备注", width: 120 },
]
const backupWarehouse = (row) => {
  ElMessageBox.confirm("是否确认完结该头程订单?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let params = {
        backup_warehouse_order_no: row.order_no,
        detail: {
          [row.to_fn_sku]: row.quantity,
        },
      }
      listingGetGoods(params).then((res) => {
        handleSubmitForm()
        ElMessage({ type: "success", message: "操作成功" })
      })
    })
    .catch(() => {
      ElMessage({ type: "info", message: "取消" })
    })
}
const pageType = ref("")
const open = (type, row) => {
  pageType.value = type
  let columns = []
  if (type == "route") {
    title.value = "FBA在途"

    columns = [...orderOptions.columns, ...routeColums]
  }
  if (type == "wait") {
    title.value = "待发货件"

    columns = [...orderOptions.columns, ...waitColums]
  }

  modelValue.value = true
  skuInfo.value = row
  nextTick(() => {
    handleSubmitForm()
  })
  setTimeout(() => {
    tableRef?.value?.loadColumn(columns)
  }, 100)
}

defineExpose({
  open,
})
</script>
<style lang="scss" scoped></style>
